﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

using Microsoft.Samples.Office.UnifiedCommunications.Gadget.EWSUtility;
using Microsoft.Samples.Office.UnifiedCommunications.Gadget.Config;
using Microsoft.Samples.Office.UnifiedCommunications.Gadget.Events;

namespace Microsoft.Samples.Office.UnifiedCommunications.Gadget
{
    public partial class EWSConfig : Page
    {
        #region Variable Declarations
        bool? _autodiscover;    // Use autodiscover for EWS settings
        string _server;         // Exchange server
        string _email;          // Email address
        string _user;           // User name
        string _domain;         // Domain
        string _password;       // Password
        string _ewsUrl;         // Exchange Web Service Url

        string _message;        // Status message
        bool _success;          // Indicates if EWS was configured successfully

        private BackgroundWorker _worker;

        private delegate void ConfigureEWSDelegate();
        private Delegate delegateConfigureEWS;

        private delegate void RaiseEWSConfiguredEventDelegate(EWSConfiguredEventArgs e);
        private Delegate raiseEWSConfiguredEvent;
        #endregion

        public EWSConfig()
        {
            InitializeComponent();

            this.btnHelp.MouseEnter += new MouseEventHandler(btnHelp_MouseEnter);
            this.btnHelp.MouseLeave += new MouseEventHandler(btnHelp_MouseLeave);

            raiseEWSConfiguredEvent = new RaiseEWSConfiguredEventDelegate(RaiseEWSConfiguredEvent);
        }

        private void BackDoubleAnimation_Completed(object sender, EventArgs e)
        {
            LoadEWSConfig();
        }

        private void ConfigureEWS()
        {
            string ewsMessage = default(string);
            bool success = false;

            try
            {
                EWSConfiguration ewsConfig = new EWSConfiguration();

                if (_autodiscover == true)
                    ewsConfig.DiscoverEWSUrl(_user, _domain, _password, _email);
                else
                    ewsConfig.ManuallyConfigureEWS(_server, _user, _domain, _password);

                if (!String.IsNullOrEmpty(ewsConfig.ewsUrl))
                {
                    _ewsUrl = ewsConfig.ewsUrl;
                    success = true;
                }

                if (success)
                {
                    SettingsEWS ewsSettings = new SettingsEWS(
                        _email, _server, string.Concat(_domain, @"\", _user), _password, _ewsUrl, (bool)_autodiscover, null, Gadget.DisplayName);
                    GadgetConfigurationManager.SetUserSettingsEWS(ewsSettings);

                    EWSConfiguredEventArgs args = new EWSConfiguredEventArgs();
                    this.Dispatcher.Invoke(DispatcherPriority.Send, raiseEWSConfiguredEvent, args);

                    ewsMessage = string.Concat("You are configured to connect to Exchange Web Services at: ",
                        Environment.NewLine, _ewsUrl);
                }
                else
                {
                    ewsMessage = string.Concat("The Autodiscover service could not be contacted, please check your entries and try again.");
                }
            }
            catch (Exception e)
            {
                ewsMessage = string.Concat("An error occurred while saving the Exchange Web Services configuration information.",
                    Environment.NewLine, "Error: ", e.Message);
            }

            _message = ewsMessage;
            _success = success;
        }

        private void LoadEWSConfig()
        {
            SettingsEWS curSettings = GadgetConfigurationManager.GetUserSettingsEWS();

            if (!string.IsNullOrEmpty(curSettings.EWSUrl) || !string.IsNullOrEmpty(curSettings.ExchangeServer))
            {
                chkAutoDiscover.IsChecked = curSettings.AutoDiscover;
                if (curSettings.AutoDiscover == false)
                    chkAutoDiscover_Unchecked(this, new RoutedEventArgs());

                txtEmailAddress.Text = curSettings.EmailAddress;
                txtServer.Text = string.IsNullOrEmpty(curSettings.ExchangeServer) ? string.Empty : curSettings.ExchangeServer;
                txtDomain.Text = curSettings.DomainUser.Split(new char[] { '\\' })[0];
                txtUserName.Text = curSettings.DomainUser.Split(new char[] { '\\' })[1];
                txtPassword.Password = curSettings.Password;
            }
            else
            {
                chkAutoDiscover.IsChecked = true;
            }
        }

        private void BeginConfigureEWS()
        {
            if (ValidateInput())
            {
                _autodiscover = chkAutoDiscover.IsChecked;
                _server = txtServer.Text.Trim();
                _email = txtEmailAddress.Text.Trim();
                _user = txtUserName.Text.Trim();
                _domain = txtDomain.Text.Trim();
                _password = txtPassword.Password;
                _ewsUrl = default(string);

                _worker = new BackgroundWorker();
                _worker.WorkerReportsProgress = false;
                _worker.WorkerSupportsCancellation = false;

                _worker.DoWork += delegate(object s, DoWorkEventArgs args)
                {

                    delegateConfigureEWS = new ConfigureEWSDelegate(ConfigureEWS);
                    this.Dispatcher.Invoke(DispatcherPriority.Background, delegateConfigureEWS);
                };

                _worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
                {
                    btnApply.IsEnabled = true;
                    gridLoading.Visibility = Visibility.Collapsed;

                    ShowMessage(_message);
                };

                _worker.RunWorkerAsync();

                ShowMessage(null);
                gridLoading.Visibility = Visibility.Visible;
                btnApply.IsEnabled = false;
            }        
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            SettingsWindow.Instance.Close();
        }

        private void btnApply_Click(object sender, RoutedEventArgs e)
        {
            BeginConfigureEWS();
        }

        private void chkAutoDiscover_Checked(object sender, RoutedEventArgs e)
        {
            spEmailAddress.Visibility = Visibility.Visible;
            spServer.Visibility = Visibility.Collapsed;
            txtServer.Text = string.Empty;
        }

        private void chkAutoDiscover_Unchecked(object sender, RoutedEventArgs e)
        {
            spEmailAddress.Visibility = Visibility.Collapsed;
            spServer.Visibility = Visibility.Visible;
            txtEmailAddress.Text = string.Empty;
        }

        private bool ValidateInput()
        {
            bool valid = true;

            string styleValidation = "ValidationStyle";

            // Reset all Styles
            //
            txtEmailAddress.Style = null;
            txtServer.Style = null;
            txtDomain.Style = null;
            txtUserName.Style = null;
            txtPassword.Style = null;
            
            if (chkAutoDiscover.IsChecked == true)
            {
                if (String.IsNullOrEmpty(txtEmailAddress.Text.Trim()))
                {
                    valid = false;
                    txtEmailAddress.Style = (Style)spEWSConfig.Resources[styleValidation];
                }
            }
            else
            { 
                if (String.IsNullOrEmpty(txtServer.Text.Trim()))
                {
                    valid = false;
                    txtServer.Style = (Style)spEWSConfig.Resources[styleValidation];
                }
            }

            if (String.IsNullOrEmpty(txtDomain.Text.Trim()))
            {
                valid = false;
                txtDomain.Style = (Style)spEWSConfig.Resources[styleValidation];
            }
            if (String.IsNullOrEmpty(txtUserName.Text.Trim()))
            {
                valid = false;
                txtUserName.Style = (Style)spEWSConfig.Resources[styleValidation];
            }
            if (String.IsNullOrEmpty(txtPassword.Password))
            {
                valid = false;
                txtPassword.Style = (Style)spEWSConfig.Resources[styleValidation];
            }

            if (valid == true)
                ShowMessage(null);
            else
                ShowMessage("Please provide values for the highlighted required fields");

            return valid;
        } 

        private void RaiseEWSConfiguredEvent(EWSConfiguredEventArgs e)
        {
            GadgetEventManager.Instance.OnEWSConfiguredEvent(e);
        }

        private void EWSForm_PreviewKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (ValidateInput())
                {
                    BeginConfigureEWS();
                }
            }
        }

        void btnHelp_MouseLeave(object sender, MouseEventArgs e)
        {
            (base.FindResource("fadeOut") as Storyboard).Begin(this.tooltip);
        }

        void btnHelp_MouseEnter(object sender, MouseEventArgs e)
        {
            (base.FindResource("fadeIn") as Storyboard).Begin(this.tooltip);
        }

        void ShowMessage(string message)
        {
            if (!String.IsNullOrEmpty(message))
            {
                gridMessage.Visibility = Visibility.Visible;
                tbMessage.Text = message;
            }
            else
            {
                tbMessage.Text = string.Empty;
                gridMessage.Visibility = Visibility.Collapsed;
            }
        }
    }
}